﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFWS.XHandler.Core;
using JKF.Substructure;
using JKF.BusinessLayer.BLL;
using JKF.Entities;
using System.Data;
using JKF.Entities.Model;
namespace JKF.HandlerLayer.Sys
{
    public partial class SysRoleHandler:AHttpHandler
    {
        private static bllSYS_ROLE bllSys_Role = new bllSYS_ROLE();
        public override void ProcessRequest()
        {
            //所有错误和异常将抛出异常.正常执行程序则在方法则返回数据
            try
            {
                this.Manager(Utils.GetActionName);
            }
            catch (Exception ex)
            {
                //将错误抛到客户端(以Json格式)
                Utils.ToClient(true, ex.Message);
                //写日志
                AppLogger.Log(ex.Message, ex);
            }
        }
        /// <summary>
        /// 此类中保存从前天回传回来的数据
        /// </summary>
        public class ROLE_MODULE_ACTION
        {
            public string ROLE_KEY { get; set; }
            /// <summary>
            /// 角色名称
            /// </summary>
            public string ROLE_NAME { get; set; }
            /// <summary>
            ///  角色名称的备注信息
            /// </summary>
            public string ROLE_DESCRIPTON { get; set; }
            /// <summary>
            /// 角色与模块关系表中数据
            /// </summary>
            public string[] ROLE_MODULE { get; set; }
            /// <summary>
            /// 角色与操作关系表中数据
            /// </summary>
            public string[] ROLE_ACTION { get; set; }
            /// <summary>
            /// 判断前台是否修改
            /// </summary>
            public bool IsChangeRole_Module_Action { get; set; }
        }
        /// <summary>
        /// 获取模块表与操作表的树行结构数据
        /// </summary>
        public void GetSysModule_ActionTree()
        {
            try
            { 
                var oList = new bllSYS_MODULE().GetSysModule_SysActionBLL();
                Response.Write(new ResponseInf
                {
                    Data = oList,
                    Success = true
                }.ToJson());
            }
            catch (Exception exp)
            {
                Response.Write(new ResponseInf { Success = false, Message = exp.Message }.ToJson());
            }
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        public void InsertRole()
        {
            try
            {
                var strScr = P("moduleObj");
                string role_key=string.Empty;
                string role_module_actionInsert = this.BuildRole_Module_RoleInsert(JsonSerializer.Deserialize<ROLE_MODULE_ACTION>(strScr), ref role_key);
                // 角色添加事件，同时需要添加三个表中的数据sys_role_action，sys_role_module，sys_role 采用事务  
                bllSys_Role.TransactionInsertRole_Module_ActionBLL(role_module_actionInsert);
                CacheManage.Remove("SysRoleOne");
                //bllDic_Level.Add(dic_LevelInfo);
                var pk = role_key;
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Message = "添加成功.", Data = pk }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 修改角色
        /// </summary>
        public void EditRole()
        {
            try
            {
                var strScr = P("moduleObj");
                string role_key = string.Empty;
                // 角色修改事件，同时需要修改三个表中的数据sys_role_action，sys_role_module，sys_role 采用事务  

                string role_module_actionUpdate = BuildRole_Module_RoleUpdate(JsonSerializer.Deserialize<ROLE_MODULE_ACTION>(strScr),ref role_key);
                // 执行脚本更新
                bllSys_Role.TransactionUpdateRole_Module_ActionBLL(role_module_actionUpdate);
                CacheManage.Remove("SysRoleOne");// 清空缓存
                var pk = role_key;
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Message = "修改成功.", Data = pk }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 删除角色级别名称
        /// </summary>
        public void DeleteRole()
        {
            try
            {
                var role_Code = P("id");
                // 角色删除事件，同时需要删除三个表中的数据sys_role_action，sys_role_module，sys_role 采用事务  
                //StringBuilder deleteRole_Module_Action = new StringBuilder(); 
                //deleteRole_Module_Action.AppendFormat("DELETE dbo.SYS_ROLE WHERE ROLE_KEY='{0}'\n\r",role_Code);
                //deleteRole_Module_Action.AppendFormat("DELETE dbo.SYS_ROLE_ACTION WHERE ROLE_KEY='{0}'\n\r", role_Code);
                //deleteRole_Module_Action.AppendFormat("DELETE dbo.SYS_ROLE_MODULE WHERE ROLE_KEY='{0}'\n\r", role_Code);
                // 采用事务删除
                //bllSys_Role.TransactionDeleteRole_Module_ActionBLL(deleteRole_Module_Action.ToString());
                string result = bllSys_Role.StoreProcedureDeleteRole_Module_ActionDAL(role_Code);
                CacheManage.Remove("SysRoleOne");
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = result, Data = role_Code }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 获取店面列表数据
        /// </summary>
        public void GetRoles()
        {
            var obj = new PagerList();

            int pageCount = 0;
            int rowCount = 0;
//ROLE_KEY, ROLE_NAME, ROLE_DESCRIPTON, DATE_CREATE, DATE_UPDATE
            obj.Entity = from a in bllSys_Role.GetSys_RolesBLL(P("ROLE_NAME"), P("PageIndex").ToInt32(), P("PageSize").ToInt32(), ref pageCount, ref rowCount).AsEnumerable()
                         select new
                         {
                             ROLE_KEY = a.Field<Guid>("ROLE_KEY").ToString(),
                             ROLE_NAME = a.Field<string>("ROLE_NAME"),
                             ROLE_DESCRIPTON = a.Field<string>("ROLE_DESCRIPTON")
                         }; 
            obj.RowCount = rowCount;
            obj.PageCount = pageCount;
            ResponseJsonObject = obj;
        }

        /// <summary>
        /// 从Json对象构建对象，用于Update
        /// </summary>
        /// <param name="shopInfo">实体对象</param>
        /// <param name="role_key">角色ID</param>
        /// <returns></returns>
        public string BuildRole_Module_RoleUpdate(ROLE_MODULE_ACTION role_module_action,ref string role_key)
        {
            StringBuilder builder = new StringBuilder(); 
            // 1. 先判断是否修改更新role_module和role_action表中数据
            builder.AppendFormat("UPDATE  dbo.SYS_ROLE SET ROLE_NAME='{0}',ROLE_DESCRIPTON='{1}' WHERE ROLE_KEY='{2}'\r\n", role_module_action.ROLE_NAME, role_module_action.ROLE_DESCRIPTON, role_module_action.ROLE_KEY);
            role_key = role_module_action.ROLE_KEY.ToString();
            if (!role_module_action.IsChangeRole_Module_Action)
            {
                // 只需更新role表中数据 
                return builder.ToString();
            } 
            // 否则就需要更新
            //2.生成Role_Module表的delete和Insert语句
            builder.AppendFormat("DELETE dbo.SYS_ROLE_MODULE WHERE ROLE_KEY='{0}'\r\n", role_module_action.ROLE_KEY);
            for (int i = 0; i < role_module_action.ROLE_MODULE.Length; i++)
            {
                builder.AppendFormat("INSERT INTO dbo.SYS_ROLE_MODULE(ROLE_KEY,MODULE_KEY) VALUES('{0}','{1}')\r\n", role_module_action.ROLE_KEY, role_module_action.ROLE_MODULE[i]);
            }
            // 3. 生成Role_Action 表中的delete 和Insert语句
            builder.AppendFormat("DELETE dbo.SYS_ROLE_ACTION WHERE ROLE_KEY='{0}'\r\n", role_module_action.ROLE_KEY);
            for (int j = 0; j < role_module_action.ROLE_ACTION.Length; j++)
            {
                builder.AppendFormat("INSERT INTO  dbo.SYS_ROLE_ACTION(ROLE_KEY,ACTION_KEY,USER_CREATE) VALUES('{0}','{1}','{2}')\r\n", role_module_action.ROLE_KEY, role_module_action.ROLE_ACTION[j], bllSYS_USER.CurrentUser.USER_KEY.ToString());
            }
            return builder.ToString();
        } 
        /// <summary>
        /// 从Json对象构建对象，用于Insert
        /// </summary>
        /// <param name="shopInfo">实体对象</param>
        /// <param name="role_key">角色ID</param>
        /// <returns></returns>
        public string BuildRole_Module_RoleInsert(ROLE_MODULE_ACTION role_module_action, ref string role_key)
        { 
            StringBuilder builder = new StringBuilder();
            role_key =  DB.HR.GetNewGuid(); // 角色表中的主键ID
            // 1.先生成角色表中的insert语句
            builder.AppendFormat("INSERT INTO dbo.SYS_ROLE(ROLE_KEY,ROLE_NAME,ROLE_DESCRIPTON) VALUES('{0}','{1}','{2}')\r\n", role_key, role_module_action.ROLE_NAME, role_module_action.ROLE_DESCRIPTON);
            //2.生成Role_Module表的Insert语句
            for (int i = 0; i < role_module_action.ROLE_MODULE.Length; i++)
            {
                builder.AppendFormat("INSERT INTO dbo.SYS_ROLE_MODULE(ROLE_KEY,MODULE_KEY) VALUES('{0}','{1}')\r\n", role_key, role_module_action.ROLE_MODULE[i]);
            }
            // 3. 生成Role_Action 表中的INsert语句
            for (int j = 0; j < role_module_action.ROLE_ACTION.Length; j++)
            {
                builder.AppendFormat("INSERT INTO  dbo.SYS_ROLE_ACTION(ROLE_KEY,ACTION_KEY,USER_CREATE) VALUES('{0}','{1}','{2}')\r\n", role_key, role_module_action.ROLE_ACTION[j], bllSYS_USER.CurrentUser.USER_KEY.ToString());
            }
            return builder.ToString(); 
        } 
        /// <summary>
        /// 根据模块level_code获得实体模块信息
        /// </summary>
        public void GetRoleByCode()
        {
            try
            {
                var scid = P("moduleKey");
                // 这里还需要获取dbo.SYS_ROLE_ACTION角色操作表、dbo.SYS_ROLE_MODULE角色模块表中的数据
                SYS_ROLEinfo sysRole = bllSys_Role.GetModel(new Guid(scid));
                if (sysRole == null)
                {
                    Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Data = "null" }));
                    return;
                }
                //获取角色操作表数据
                List<SYS_ROLE_ACTIONinfo> role_actionList = new bllSYS_ROLE_ACTION().GetListArray("ROLE_KEY='"+sysRole.ROLE_KEY.ToString()+"'");
                List<SYS_ROLE_MODULEinfo> role_moduleList = new bllSYS_ROLE_MODULE().GetListArray("ROLE_KEY='" + sysRole.ROLE_KEY.ToString() + "'");
                ROLE_MODULE_ACTION role_module_action = new ROLE_MODULE_ACTION();
                role_module_action.ROLE_KEY = sysRole.ROLE_KEY.ToString();
                role_module_action.ROLE_NAME = sysRole.ROLE_NAME;
                role_module_action.ROLE_DESCRIPTON = sysRole.ROLE_DESCRIPTON;
                role_module_action.ROLE_ACTION = role_actionList.Select<SYS_ROLE_ACTIONinfo, string>(a=>a.ACTION_KEY.ToString()).ToArray();
                role_module_action.ROLE_MODULE = role_moduleList.Select<SYS_ROLE_MODULEinfo, string>(a => a.MODULE_KEY.ToString()).ToArray(); 
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Data = role_module_action }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 检查已输入名称是否存在
        /// </summary>
        public void CheckRoleName()
        {
            try
            {
                var sys_role_name = P("ROLE_NAME");
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Data = bllSys_Role.ExistsSysRoleNameBLL(sys_role_name) }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
    }
}
